<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/6/24
 * Time: 14:36
 */

namespace app\logic\cron;


use app\common\lib\Common;
use app\common\lib\RedisQueue;
use app\common\lib\Spreadsheet;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\image\ImageCommandPlanModel;
use app\model\novel\NovelBusinessModel;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelChapterPartModel;
use app\model\novel\NovelSpreadModel;
use app\model\plan\PromotionPlanModel;
use app\model\plan\PromotionPlanPartImageModel;
use app\model\plan\PromotionPlanWorkModel;
use app\model\plan\PromotionPlanWorkPartModel;
use support\Db;

class PlanWorkLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
//        if (is_object(self::$instance)) {
//            return self::$instance;
//        }

        return  new self();
    }

    public function autoGeneratePlanWorkAiImage()
    {
        //获取开启商家
        $bWhere = ['status'=>1,'isdel'=>0,['spread_type','in',[1,2]]];
        $businessIds = NovelBusinessModel::getInstance()->getWhere($bWhere)->pluck('id')->toArray();

        //获取正常小说
        $nWhere = [
            'status'=>1,
            'isdel'=>0,
            ['spread_type','in',[1,2]],
            ['business_id','in',$businessIds],
        ];
        $novelSns1 = NovelSpreadModel::getInstance()->getWhere($nWhere)->where(['task_status'=>2])->pluck('novel_sn')->toArray();
        $novelSns2 = NovelSpreadModel::getInstance()->getWhere($nWhere)->where(['under_status'=>1])->pluck('novel_sn')->toArray();
        $novelSns = array_unique(array_merge($novelSns1,$novelSns2));
        $where = [
            'status'=>1,
            'isdel'=>0,
            ['part_nums','>',0],
            ['novel_sn','in',$novelSns],
        ];
        $planData = PromotionPlanModel::getInstance()->getWhere($where)->orderBy('created_at','desc')->get();
        foreach($planData as $plan){
            $this->generatePlanWorkAiImage($plan);
        }

        return ['success'];
    }

    protected function generatePlanWorkAiImage($plan)
    {
        //获取该方案的段落
        $batch = NovelChapterPartModel::getInstance()->getWhere(['planid' => $plan['id'], 'isdel' => 0])->orderBy('batch', 'desc')->value('batch');
        $parts = NovelChapterPartModel::getInstance()->getWhere(['planid' => $plan['id'], 'isdel' => 0, 'batch' => $batch])->orderBy('number', 'asc')->get();
        if (empty($parts)) {
            return [];
        }

        //todo 插入用户推文方案片段
        $userPartInserts = [];
        foreach ($parts as $part) {
            $count = PromotionPlanPartImageModel::getInstance()->getWhere(['partid'=>$part['id'],['status','in',[0,1]]])->count();
            if($count>=3){
                continue;
            }

            //每个段落生成3条记录
            foreach ([1,2,3] as $v){
                $userPartInsert = [
                    'partid'=>$part['id'],
                    'planid'=>$part['planid'],
                    'chapterid'=>$part['chapterid'],
                    'novel_sn'=>$part['novel_sn'],
                    'content'=>$part['content']??'',
                    'prompt'=>$part['prompt']??'',
                    'ai_image_command'=>$plan['ai_image_command']??'',
                    'ai_image_command_id'=>$plan['ai_image_command_id']??'0',
                    'ai_image_command_seed'=>$part['ai_image_command_seed']??'',
                    'refer_image'=>$part['refer_image']??'',
                    'more_people_prompt'=>$part['more_people_prompt']??'',
                ];

                $userPartInserts[] = $userPartInsert;
            }
        }

        if($userPartInserts){
            PromotionPlanPartImageModel::getInstance()->insert($userPartInserts);

            //生成唯一的请求id
            $requestId = Common::getRequestId();

            // 队列名
            $queue = 'asyncGeneratedPlanPartImage';
            // 数据，可以直接传数组，无需序列化
            $data = ['requestid' => $requestId, 'planid' => $plan['id'],'created_at'=>date('Y-m-d H:i:s',(time()-60))];
            // 投递消息
            RedisQueue::getInstance()->sendQueue($queue, $data);
        }

        return true;
    }
}